package com.imooc.miaosha.util;


import com.imooc.miaosha.constant.Md5Constant;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 模块描述: <br>
 * (MD5密码生成类)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/15 17:25
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Component
public class Md5Utils {


    /**
     * 执行md5密码
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        String s = DigestUtils.md5Hex(str);
        return s;
    }

    /**
     * 客户端密码拼接并加密
     *
     * @param inputPass
     * @return
     */
    public static String inputPassToFormPass(String inputPass) {
        Md5Constant md5Constant = new Md5Constant();
        String inputSalt = md5Constant.getSale();
        String str = "" + inputSalt.charAt(0) + inputSalt.charAt(2) + inputPass + inputSalt.charAt(5) + inputSalt.charAt(4);
        return md5(str);
    }

    /**
     * 将加密过一次的密码再次加密
     *
     * @param form
     * @param salt
     * @return
     */
    public static String formPassToDBPass(String form, String salt) {
        String str = "" + salt.charAt(0) + salt.charAt(2) + form + salt.charAt(5) + salt.charAt(6);
        return md5(str);
    }

    /**
     * 加密对外方法
     *
     * @param input
     * @param salt
     * @return
     */
    public static String inputPassToDbPass(String input, String salt) {
        String firstAuth = inputPassToFormPass(input);
        if (!StringUtils.isEmpty(firstAuth)) {
            String secondPass = formPassToDBPass(firstAuth, salt);
            return secondPass;
        }
        return null;
    }

}
